package com.cqyanyu.yanyu.utils;

import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import com.cqyanyu.yanyu.http.XCallback;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 倒计时处理器
 * Created by cheng on 2016/7/6.
 */
public class CountdownUtil implements XCallback<Boolean> {
    static final int COUNTDOWN = 60;//倒计时
    String countdownTemplate = "%d";
    String text;
    TextView textView;
    Timer timer = new Timer(true);
    private int s;

    public CountdownUtil(TextView textView, String text) {
        this.textView = textView;
        this.text = text;
    }

    @Override
    public void onSuccess(Boolean result) {
        if (result) {
            s = COUNTDOWN;
            textView.setText(s + "");
            textView.setEnabled(false);
            timer.schedule(timerTask, 1000, 1000); //延时1000ms后执行，1000ms执行一次
        }
    }

    @Override
    public void onFinished() {

    }

    /**
     * 设置占位符模板
     *
     * @param countdownTemplate
     */
    public void setCountdownTemplate(String countdownTemplate) {
        this.countdownTemplate = countdownTemplate;
    }

    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (s <= 0) {
                        textView.setText(text);
                        textView.setEnabled(true);
                        timer.cancel();
                    } else {
                        textView.setText(String.format(countdownTemplate, s));
                    }

            }
        }
    };
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            s--;
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };
}
